package algorithm.quartile;

import java.util.Collections;
import java.util.List;
import java.util.Vector;

import util.VectorMath;

import algorithm.RADDACL_Cluster;
import algorithm.Region;

public class DistanceTable_Centroid extends DistanceTable
{
	protected Vector<Double> centroid;
	protected Region region;
	
	public DistanceTable_Centroid(RADDACL_Cluster parent,
			Region region) {
		super(parent);
		
		this.region = region;
	}

	public Vector<Double> getCentroid()
	{
		return this.centroid;
	}

	@Override
	public void generateDistanceTable() 
	{
		calculateCentroid(parent);
		
		for(Integer index: this.region.getIndexes())
		{
			parent.getInput().get(index);
			
			this.distances.add(	
					new Distance_Centroid( 
						index,
						VectorMath.euclidianDistance(parent.getInput().get(index), getCentroid())
					)
				);
		}
		
		Collections.sort(distances);
	}
	
	@SuppressWarnings("unchecked")
	protected void calculateCentroid(RADDACL_Cluster parent) 
	{
		// Add up all the centroids
		for (Integer index : this.region.getIndexes()) {
			if (centroid == null) 
			{
				this.centroid = (Vector<Double>) parent.getInput().get(index)
						.clone();
			} 
			else
			{
				VectorMath.add(this.centroid, parent.getInput().get(index));
			}
		}

		// Divide centroid by the number of inputs
		for (int i = 0; i < this.centroid.size(); i++) 
		{
			this.centroid.set(i, this.centroid.get(i)
					/ (double) this.region.getIndexes().size());
		}
	}
}
